package com.adams.custom.page.mgt.dao.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.adams.access.db.bean.DicColumn;
import com.adams.access.db.bean.ViewItem;
import com.adams.access.db.bean.ViewPanel;
import com.adams.access.db.dao.hibernate.HibernateGenericDao;
import com.adams.core.exception.BusinessException;
import com.adams.custom.page.core.service.DicTableService;
import com.adams.custom.page.util.ViewCacheUtil;

/**
 * 
 * File Name : ViewItemDaoImpl.java
 * 
 * @Description : 页面信息项实体数据访问实现类
 */
public class ViewItemDaoImpl extends HibernateGenericDao<ViewItem, Long>
{

	private static String cacheItemMapByPk_key = "ViewItem_cacheItemMapByPk";

	private static String cacheItemMapByViewPanelid_key = "ViewItem_cacheItemMapByViewPanelid";

	/**
	 * Description : 数据字典服务接口 Author : 904370
	 */
	private DicTableService dicTableService;

	/**
	 * Description : 页面面板实体数据访问实现类 Author : 904370
	 */
	private ViewPanelDaoImpl viewPanelDaoImpl;

	public void setViewPanelDaoImpl(ViewPanelDaoImpl viewPanelDaoImpl)
	{
		this.viewPanelDaoImpl = viewPanelDaoImpl;
	}

	public void setDicTableService(DicTableService dicTableService)
	{
		this.dicTableService = dicTableService;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.adams.access.db.dao.hibernate.HibernateGenericDao#save(java
	 * .lang.Object)
	 */
	public void save(ViewItem model)
	{
		super.save(model);
	}

	/**
	 * Description : 从缓存中根据id获得ViewItem对象
	 * 
	 * @param id
	 * @return
	 * @throws BusinessException
	 * 
	 */
	@SuppressWarnings("unchecked")
	public ViewItem getByCache(Serializable id) throws BusinessException
	{
		String key = id + "";
		Map cacheItemMapByPk = ViewCacheUtil
				.getConfigDataCacheMap(cacheItemMapByPk_key);
		if (!cacheItemMapByPk.containsKey(key))
		{
			synchronizationCache();
		}
		return (ViewItem) cacheItemMapByPk.get(key);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.adams.access.db.dao.hibernate.HibernateGenericDao#delete(java
	 * .lang.Object)
	 */
	public void delete(ViewItem model)
	{
		super.delete(model);
	}

	/**
	 * Description : 删除ViewItem对象列表
	 * 
	 * @param model
	 * 
	 */
	public void deleteAll(List<ViewItem> models)
	{
		for (ViewItem model : models)
		{
			super.delete(model);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.adams.access.db.dao.hibernate.HibernateGenericDao#saveOrUpdate
	 * (java.lang.Object)
	 */
	public void saveOrUpdate(ViewItem model)
	{
		super.saveOrUpdate(model);
	}

	/**
	 * Description : 根据界面面板得到ViewItem列表
	 * 
	 * @param viewpanelid
	 * @return
	 * @throws BusinessException
	 * 
	 */
	@SuppressWarnings("unchecked")
	public List<ViewItem> findItemByViewPanelid(Long viewpanelid)
			throws BusinessException
	{
		logger.info("parameter viewpanelid=" + viewpanelid);
		String key = viewpanelid + "";
		Map cacheItemMapByViewPanelid = ViewCacheUtil
				.getConfigDataCacheMap(cacheItemMapByViewPanelid_key);
		if (!cacheItemMapByViewPanelid.containsKey(key))
		{
			synchronizationCache();
		}
		List<ViewItem> result = new ArrayList<ViewItem>();
		List<ViewItem> temp = (List<ViewItem>) cacheItemMapByViewPanelid
				.get(key);
		if (null != temp && temp.size() > 0)
		{
			result.addAll(temp);
			// sortItemById(result);
		}
		logger.info("result list size=" + result.size());
		return result;
	}

	private void sort(List<ViewItem> result)
	{
		if (null == result || result.size() == 0)
		{
			return;
		}
		Collections.sort(result, new Comparator<ViewItem>()
		{
			@Override
			public int compare(ViewItem o1, ViewItem o2)
			{
				if (o1.getOrderid() > o2.getOrderid())
				{
					return 1;
				} else if (o1.getOrderid() == o2.getOrderid())
				{
					if (o1.getId() > o2.getId())
					{
						return 1;
					} else if (o1.getId() == o2.getId())
					{
						return 0;
					}
					return -1;
				}
				return -1;
			}
		});
	}

	/**
	 * Description : 获得所有ViewItem对象
	 * 
	 * @return
	 * @throws BusinessException
	 * 
	 */
	@SuppressWarnings("unchecked")
	public List<ViewItem> findAll() throws BusinessException
	{
		List<ViewItem> result = null;
		Map cacheItemMapByPk = ViewCacheUtil
				.getConfigDataCacheMap(cacheItemMapByPk_key);
		if (cacheItemMapByPk.size() == 0)
		{
			result = synchronizationCache();
			return result;
		} else
		{
			result = new ArrayList<ViewItem>();
			Set keySet = cacheItemMapByPk.keySet();
			for (Iterator it = keySet.iterator(); it.hasNext();)
			{
				Object key = it.next();
				ViewItem temp = (ViewItem) cacheItemMapByPk.get(key);
				if (null != temp)
				{
					result.add(temp);
				}
			}
		}
		sort(result);
		return result;
	}

	private List<ViewItem> findItemAllFromDB()
	{
		List<ViewItem> result = query("from ViewItem");
		return result;
	}

	/**
	 * Description : 同步缓存
	 * 
	 * @return
	 * @throws BusinessException
	 * 
	 */
	@SuppressWarnings("unchecked")
	public synchronized List<ViewItem> synchronizationCache()
			throws BusinessException
	{
		List<ViewItem> result = findItemAllFromDB();
		Map cacheItemMapByPk = ViewCacheUtil
				.getConfigDataCacheMap(cacheItemMapByPk_key);
		Map cacheItemMapByViewPanelid = ViewCacheUtil
				.getConfigDataCacheMap(cacheItemMapByViewPanelid_key);
		cacheItemMapByViewPanelid.clear();
		for (ViewItem viewItem : result)
		{
			try
			{
				viewItem = setNameNoEnumerateTag(viewItem);
			} catch (BusinessException e)
			{
				logger.error("配置出错 t_view_info表id:" + viewItem.getId(), e);
			}
			cacheItemMapByPk.put(viewItem.getId() + "", viewItem);

			String viewpanelidStr = viewItem.getViewpanelid() + "";
			List<ViewItem> viewpanelList = null;
			if (cacheItemMapByViewPanelid.containsKey(viewpanelidStr))
			{
				viewpanelList = (List<ViewItem>) cacheItemMapByViewPanelid
						.get(viewpanelidStr);
			} else
			{
				viewpanelList = new ArrayList<ViewItem>();
			}
			viewpanelList.add(viewItem);
			cacheItemMapByViewPanelid.put(viewpanelidStr, viewpanelList);
		}

		// 排序处理
		Set<String> viewPanelids = cacheItemMapByViewPanelid.keySet();
		for (String viewPanelid : viewPanelids)
		{
			List<ViewItem> viewItems = (List<ViewItem>) cacheItemMapByViewPanelid
					.get(viewPanelid);
			sort(viewItems);
			cacheItemMapByViewPanelid.put(viewPanelid, viewItems);
		}

		ViewCacheUtil.put2ConfigDataCacheMap(cacheItemMapByPk_key,
				cacheItemMapByPk);
		ViewCacheUtil.put2ConfigDataCacheMap(cacheItemMapByViewPanelid_key,
				cacheItemMapByViewPanelid);
		return result;
	}

	/**
	 * Description : 对原字段项名经过处理 产生不包含枚举标识的字段项名，并设入viewItem对象中
	 * 
	 * @param viewItem
	 * @throws BusinessException
	 * 
	 */
	private ViewItem setNameNoEnumerateTag(ViewItem viewItem)
			throws BusinessException
	{
		// 当倒数第二字段为枚举时，并且最倒数第一字段为枚举的key或者value时
		// 把倒数第一的字段从viewitem中name中去除
		ViewPanel viewPanel = this.viewPanelDaoImpl.get(viewItem
				.getViewpanelid());
		String tablecode = viewPanel.getTablecode();
		DicColumn finalDicColumn = dicTableService.getFinalDicColumn(tablecode,
				viewItem.getColumncodes());
		List<String> columncodes = viewItem.getColumncodes();
		int columncodeslen = columncodes.size();
		String name = viewItem.getName();
		if (columncodeslen > 1)
		{
			String lastcolumncode = columncodes.get(columncodeslen - 1);
			String lastsecondlycolumncode = columncodes.get(columncodeslen - 2);
			if (DicColumn.ENUMERATE_TAG_SET.contains(lastcolumncode)
					&& finalDicColumn.getDicColumnPK().getColumncode().equals(
							lastsecondlycolumncode))
			{
				name = name.substring(0, name.lastIndexOf(ViewItem.NAME_SEQ));
			}
		}
		viewItem.setNameNoEnumerateTag(name);
		return viewItem;
	}
}
